package com.ht.psplan;

import org.apache.log4j.Logger;

import java.rmi.Naming;
import java.util.ResourceBundle;

/**
 * @author Dond Shufeng
 *         Date: 2007-2-13
 *         Time: 10:36:01
 */
public class PlanCurveSenderFactory {
    private static final String Server_IP = "PlanServer.ip";
    public static final String RMI_SERVER_HOST_PROPERTY = "rmiServerHost";
    public static final String RMI_SERVER_PORT_PROPERTY = "rmiServerPort";

    private static Logger log = Logger.getLogger(PlanCurveSenderFactory.class);

    //private static int port = 1099;

    public static PlanCurveSender getSender() {
        PlanCurveSender server = null;
        //String hostName = System.getProperty(RMI_SERVER_HOST_PROPERTY);
        //String hostPort = System.getProperty(RMI_SERVER_PORT_PROPERTY);
        //if (hostPort != null)
        //    port = Integer.parseInt(hostPort);
        //SpecifiedSocketFactory.setSpecifiedSocket();
        //if (hostName != null) {
        //    SpecifiedSocketFactory.setMappingHost(hostName);
        //    try {
        //        server = (PlanCurveSender) Naming.lookup("//" + hostName +":"+ port + "/" + PlanCurveSender.class.getName());
        //    } catch (Exception e) {
        //        log.error(e);
        //        e.printStackTrace();
        //    }
        //}
        //if (server != null) return server;
        //System.setProperty(SpecifiedSocketFactory.RMI_SERVER_PORT_PROPERTY, "8087");
        ResourceBundle rb = ResourceBundle.getBundle("config.SenderServer");
        for (int i = 1; i < 5; i++) {
            try {
                String ip = rb.getString(Server_IP + i);
                if (ip == null || ip.trim().equals("") || ip.trim().toUpperCase().equals("NULL"))
                    continue;
                int port = Integer.parseInt(rb.getString(Server_IP + i + ".port"));

                //SpecifiedSocketFactory.setMappingHost(ip);
                server = (PlanCurveSender) Naming.lookup("//" + ip + ":" + port + "/" + PlanCurveSender.class.getName());
                if (server != null)
                    return server;
                //for (int j = 0; j < 2; j++) {
                //    try {
                //        if (j % 2 == 0) {
                //            SpecifiedSocketFactory.setMappingHost(ip);
                //        } else {
                //            SpecifiedSocketFactory.setMappingHost(null);
                //        }
                //        server = (PlanCurveSender) Naming.lookup("//" + ip + ":" + port + "/" + PlanCurveSender.class.getName());
                //    } catch (Exception e) {
                //    }
                //    if (server != null)
                //        return server;
                //}
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
